package lionel.MyController;

import lionel.input.JInput;
import lionel.input.JInputDevice;
import wiiremotej.WiiRemote;
import wiiremotej.WiiRemoteJ;
import wiiremotej.event.WRIREvent;
import wiiremotej.event.WiiDeviceDiscoveredEvent;
import wiiremotej.event.WiiDeviceDiscoveryListener;

public class MyControllersDiscoverer implements WiiDeviceDiscoveryListener {
	static org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(MyControllersDiscoverer.class.getName());

	MyControllersListener myControllersListener;
	int wiimoteCount = 0;

	public MyControllersDiscoverer(MyControllersListener lst)
	{
		myControllersListener = lst;
		// Go through JInput devices
		try
		{
			if ( JInput.isAvailable())
			{
				JInput.pollAllDevices();
				if ( JInput.getNumDevices()>0)
				{
					for (JInputDevice device: JInput.getDevices() )
					{
						log.debug("Attaching to JInput device "+device);
						MyControllerJInputImpl controller = new MyControllerJInputImpl( device.getName() );
						device.addAxisEventListener(controller);
						device.addButtonEventListener(controller);					
						myControllersListener.addDevice((MyController) controller);
						device.doPolling(true);
					}
				}
			}
		}
		catch (Exception e)
		{ log.warn("Got exception while enabling JInput "+e);  }
		// Enable the wiimote discovery
		try
		{ if (! WiiRemoteJ.isFindInProgress() )
			WiiRemoteJ.findRemotes(this); } 
		catch (Exception e)
		{ log.warn("Got exception while enabling wiimote support "+e );}
	}

	public void findFinished(int numberFound) {
		log.debug("Search Wiimote finished, found "+numberFound+" devices");
	}

	public synchronized void wiiDeviceDiscovered(WiiDeviceDiscoveredEvent evt) {
		try{			
			WiiRemote remote = (WiiRemote) evt.getWiiDevice();
			if (remote != null)
			{
				wiimoteCount++;
				log.debug("Attaching to Wiimote "+wiimoteCount);			
				MyControllerJWiimoteImpl controller = new MyControllerJWiimoteImpl( "WiiMote "+wiimoteCount, remote );
				remote.addWiiRemoteListener(controller);
				myControllersListener.addDevice((MyController) controller);
				boolean leds[] = new boolean[4];
				for (int i=0; i<4; i++)
					leds[i] = ( ( (wiimoteCount)&(1<<i) ) == (1<<i) );
				remote.setLEDLights(leds);
				if (remote.isAccelerometerEnabled())
					remote.setAccelerometerEnabled(false);
				if (remote.isSpeakerEnabled())
					remote.setSpeakerEnabled(false);
				if (remote.isIRSensorEnabled())
					remote.setIRSensorEnabled(false, WRIREvent.BASIC);
				remote.vibrateFor(250);

			}
		} catch (Exception e) {
			log.warn("Got IO Exception: "+e.toString() );
			e.printStackTrace();
		}		
	}
}
